package com.icarsaas.saas.tenant.system.service;

import com.icarsaas.saas.common.page.SoulPage;
import com.icarsaas.saas.tenant.system.model.Message;
import com.icarsaas.saas.tenant.system.repository.MessageRepository;
import com.icarsaas.saas.tenant.system.repository.MessageUserRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

@Service
public class MessageService {
	@Autowired private MessageRepository messageRepository;
	@Autowired private MessageUserRepository messageUserRepository;

	@Transactional(readOnly = false, value = "tenantTransactionManager")
	public Message save(Message entity) {
		return messageRepository.save(entity);
	}

	/**
	 * 查找个人的消息
	 * @param page
	 * @param params
	 * @return
	 */
	public SoulPage<Map<String, Object>> listSoulData(SoulPage<Map<String, Object>> page, Map<String, Object> params) {
		StringBuffer sql = new StringBuffer("select * from sys_message_user smu left join sys_message sm " +
				"on smu.ref_id=sm.id t where 1=1 ");
		if (params != null && params.size() > 0) {
			for (String key : params.keySet()) {
				String value = (String) params.get(key);
				if (StringUtils.isNotEmpty(value)) {
					if (key.equalsIgnoreCase("type")) {
						sql.append(" and t." + key + "='" + value + "'");
					} else {
						sql.append(" and t." + key + " like '%" + value + "%'");
					}
				}

			}
		}
		SoulPage<Map<String, Object>> pageResult = messageUserRepository.findBySqlForSoul(page, sql.toString(), Map.class);
		return pageResult;
	}
}
